package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.SetmealGroupMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealGroupMapper setmealGroupMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Transactional
    public void addSetmeal(Setmeal setmeal, List<Integer> checkGroupIds) {
        //1、添加套餐的基础信息
        setmealMapper.addsetMeal(setmeal);
        redisTemplate.opsForSet().add("imgFileLocal",setmeal.getImg());

        Integer id = setmeal.getId();

        //获取到套餐对应的id，在1中就需要获取到
        Map map = new HashMap<>();
        for (Integer checkGroupId : checkGroupIds) {
            map.put("setmealId", id);
            map.put("checkGroupId", checkGroupId);
            //插入检查组和套餐的关系
            setmealGroupMapper.addsetMealGroup(map);
        }
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize()); //自动分页查询

        Page<Setmeal> page=setmealMapper.pageQuery(queryPageBean);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 根据ID查询套餐
     * @param id
     * @return
     */
    public Setmeal getByid(Integer id) {
        return setmealMapper.getById(id);
    }

    /**
     * 套餐编辑功能
     * @param setmeal
     * @param checkGroupIds
     */
    @Transactional
    public void edit(Setmeal setmeal, List<Integer> checkGroupIds) {
        //事务管理
        //先编辑基础信息
        setmealMapper.editsetmeal(setmeal);
        redisTemplate.opsForSet().add("imgFileLocal",setmeal.getImg());
        Integer id1 = setmeal.getId();
        if (id1!=null){
            //根据检查组id，先清空检查组和套餐的关系表数据
            Integer id = setmeal.getId();
            setmealGroupMapper.delete(id);

            //获取到套餐对应的id，在1中就需要获取到
            Map map = new HashMap<>();
            for (Integer checkGroupId : checkGroupIds) {
                map.put("setmealId", id);
                map.put("checkGroupId", checkGroupId);
                //插入检查组和套餐的关系
                setmealGroupMapper.addsetMealGroup(map);
            }
        }
    }
}
